<?php

/**
 * 
 * @project     : innoTweets 1.0
 * @author      : Dino (DBK)
 * 
 * @package     : Some helper functions
 * 
 */
// Calculate time ago of a given datetime from now
function time_ago($ptime) {
  $ptime = strtotime($ptime);
  if ($ptime) {
    $etime = time() - $ptime;
    if ($etime < 1)
      return 'few seconds';
    $a = array(
        12 * 30 * 24 * 60 * 60 => 'year',
        30 * 24 * 60 * 60 => 'month',
        24 * 60 * 60 => 'day',
        60 * 60 => 'hour',
        60 => 'minute',
        1 => 'second'
    );
    foreach ($a as $secs => $str) {
      $d = $etime / $secs;
      if ($d >= 1) {
        $r = round($d);
        return $r . ' ' . $str . ($r > 1 ? 's' : '') . '';
      }
    }
  }
  return '0';
}

// Calculate days ago of a given date from now
function days_ago($from_date = NULL) {
  $days = 0;
  if (strtotime($from_date)) {
    $your_date = strtotime($from_date);
    $datediff = time() - $your_date;
    $days = floor($datediff / (60 * 60 * 24));
  }
  return $days;
}

// Gets the number of unread wall posts count of current user
function get_notifictaion_count() {
  $ci = & get_instance();
  $get_unread_wall_post = $ci->wall_model->get_unread_wall_post($ci->current_user['user_id']);
  if ($get_unread_wall_post['status'] == 1 && !empty($get_unread_wall_post['result'])) {
    return $get_unread_wall_post['count'];
  }
  return 0;
}

// Checks weather the current user likes a post (tweet, reply , etc..)
function get_user_like_status($like_type = NULL, $like_type_id = NULL) {
  $ci = & get_instance();
  $result = array('status' => 'no', 'total_count' => 0);
  $get_like = $ci->like_model->get_like($like_type, $like_type_id);
  if (isset($ci->current_user['user_id'])) {
    $get_user_like = $ci->like_model->get_like($like_type, $like_type_id, $ci->current_user['user_id']);
  } elseif (isset($ci->mobile_current_user['user_id'])) {
    $get_user_like = $ci->like_model->get_like($like_type, $like_type_id, $ci->mobile_current_user['user_id']);
  } else {
    $get_user_like = $ci->like_model->get_like($like_type, $like_type_id, NULL);
  }
  if ($get_user_like['status'] == 1 && !empty($get_user_like['result'])) {
    $result['status'] = 'yes';
  } else {
    $result['status'] = 'no';
  }
  $result['total_count'] = (int) $get_like['count'];
  return $result;
}

// Get comments count
function get_comments($comment_type = NULL, $comment_type_id = NULL) {
  $ci = & get_instance();
  $get_comment = $ci->comment_model->get_comments($comment_type, $comment_type_id, null);
  if (!empty($get_comment['result'])) {
    return $get_comment['result'];
  } else {
    return array();
  }
}

// Reterive the like details of a post (tweet, reply , etc..)
function get_like_type_data($like_type = NULL, $like_type_id = NULL) {
  $ci = & get_instance();
  if ($like_type == 'tweet') {
    $like_type_data = $ci->tweet_model->get_tweet_by_id($like_type_id);
  } else if ($like_type == 'reply') {
    $like_type_data = $ci->tweet_model->get_reply_by_id($like_type_id);
  } else if ($like_type == 'event') {
    $like_type_data = $ci->event_model->get_event_by_id($like_type_id);
  } else if ($like_type == 'album') {
    $like_type_data = $ci->album_model->get_album_by_id($like_type_id);
  } else if ($like_type == 'photo' || $like_type == 'video') {
    $like_type_data = $ci->album_model->get_photo_by_id($like_type_id);
  } else if ($like_type == 'wall_post') {
    $like_type_data = $ci->wall_model->get_wall_post_by_id($like_type_id);
  } else if ($like_type == 'poll') {
    $like_type_data = $ci->poll_model->get_poll_by_id($like_type_id, NULL);
  } else if ($like_type == 'comment') {
    $like_type_data = $ci->comment_model->get_comment_by_id($like_type_id);
  } else {
    $like_type_data = array('status' => '', 'result' => '');
  }
  if ($like_type_data['status'] == 1 && !empty($like_type_data['result'])) {
    return $like_type_data['result'];
  }
  return FALSE;
}

// Returns the number of replies for a poll option
function get_poll_reply_count($poll_option_id = NULL) {
  $ci = & get_instance();
  $reply_option_count = 0;
  if (!empty($poll_option_id) && is_numeric($poll_option_id)) {
    $get_poll_reply_option_count = $ci->poll_model->get_poll_reply_option_count($poll_option_id);
    if ($get_poll_reply_option_count['status'] == 1 && !empty($get_poll_reply_option_count['result'])) {
      $reply_option_count = $get_poll_reply_option_count['count'];
    }
  }
  return $reply_option_count;
}

// Returns the user details by given user id
function get_user_details_by_id($user_id = NULL) {
  $ci = & get_instance();
  $user_details = NULL;
  if (!empty($user_id) && is_numeric($user_id)) {
    $get_user_by_id = $ci->user_model->get_user_by_id($user_id);
    if ($get_user_by_id['status'] == 1 && !empty($get_user_by_id['result'])) {
      $user_details = $get_user_by_id['result'];
    }
  }
  return $user_details;
}

// Returns the group event results of a group
function get_event_result_details($event_id = NULL, $group_id = NULL) {
  $ci = & get_instance();
  $event_result = NULL;
  if (!empty($event_id) && !empty($group_id)) {
    $get_group_event_result_by_group = $ci->group_model->get_group_event_result_by_group($event_id, $group_id);
    if ($get_group_event_result_by_group['status'] == 1 && !empty($get_group_event_result_by_group['result'])) {
      $event_result = $get_group_event_result_by_group['result'];
    }
  }
  return $event_result;
}

// Checks wheater a user is online or offline
// Calculates according to the user's last activity time
function is_online($user_id = NULL) {
  $ci = & get_instance();
  if (!empty($user_id) && is_numeric($user_id)) {
    $get_user_by_id = $ci->user_model->get_user_by_id($user_id);
    if ($get_user_by_id['status'] == 1 && !empty($get_user_by_id['result'])) {
      $time_diff = @(strtotime(date('Y-m-d H:i:s')) - strtotime($get_user_by_id['result']['user_online_date']));
      if ($time_diff < 60) { // 30 Seconds
        return TRUE;
      }
    }
  }
  return FALSE;
}

// Setting the csrf token
// Used via a hidden field in every form (Not using due to some issues in session flash data)
function set_csrf_token() {
  $ci = & get_instance();
  $csrf_token = md5(microtime() . time());
  $ci->session->set_flashdata($csrf_token, $csrf_token);
  $ci->session->flashdata($csrf_token);
  return $csrf_token;
}

// Checks the submitted csrf token
// Need to call in every form submit (Not using due to some issues in session flash data)
function check_csrf_token() {
  $ci = & get_instance();
  $token = $ci->input->post('csrf_token', TRUE);
  if (!empty($token)) {
    $csrf_token = $ci->session->flashdata($token);
    if (!empty($csrf_token) && ($csrf_token == $token)) {
      return TRUE;
    }
  }
  return FALSE;
}

// Writes log file in (application/logs) folder
function system_log($name = NULL, $msg = NULL) {
  if (!empty($name) && !empty($msg)) {
    $log_path = APPPATH . 'logs/' . $name . '/';
    $filepath = $log_path . $name . '_' . date('m_Y') . '.txt';
    $msg = date("d-m-Y H:i:s") . ' --> ' . $msg . "\n";
    @mkdir($log_path, 0775, TRUE);
    $fp = @fopen($filepath, FOPEN_WRITE_CREATE);
    if ($fp) {
      @flock($fp, LOCK_EX);
      @fwrite($fp, $msg);
      @flock($fp, LOCK_UN);
      @fclose($fp);
      @chmod($filepath, FILE_WRITE_MODE);
    }
  }
  return;
}

// Getting ignores
function get_ignore_count($ignore_type = NULL, $ignore_type_id = NULL) {
  $ci = & get_instance();
  $get_ignore = $ci->ignore_model->get_ignore($ignore_type, $ignore_type_id);
  return $get_ignore['count'];
}

// Checking weather a given user is admin or not
function check_is_admin($user_name = NULL) {
  $ci = & get_instance();
  $admin_users = $ci->config->item('admins');
  if (!empty($admin_users) && is_array($admin_users)) {
    if (in_array($user_name, $admin_users)) {
      return TRUE;
    }
  }
  return FALSE;
}

/**
 * Set & Get user ids of current viewers of tweet
 * 
 * Using PHP APC
 * 
 */
function tweet_viewers($tweet_id = NULL) {

  $ci = & get_instance();

  // Checking tweet id
  if (!empty($tweet_id) && is_numeric($tweet_id)) {

    // Init vars
    $user_ids = array();
    $new_viewers = array();

    // Getting current online users from cache varibale
    $tweet_viewers = $ci->cache->get('viewers_tweet_' . $tweet_id);

    // Making current online users
    if (!empty($tweet_viewers) && is_array($tweet_viewers)) {
      foreach ($tweet_viewers as $viewer => $time) {
        $time_diff = (int) @(strtotime(date('Y-m-d H:i:s')) - strtotime($time));
        if (($time_diff < 60) && is_online($viewer)) {
          $new_viewers[$viewer] = $time;
        }
      }
    }

    // Setting updating current user's time, if needed
    if (isset($ci->current_user['user_id'])) {
      $user_id = $ci->current_user['user_id'];
      $new_viewers[$user_id] = date('Y-m-d H:i:s');
    } elseif (isset($ci->mobile_current_user['user_id'])) {
      $user_id = $ci->mobile_current_user['user_id'];
      $new_viewers[$user_id] = date('Y-m-d H:i:s');
    }

    // Saving new data to cache variable
    $ci->cache->save('viewers_tweet_' . $tweet_id, $new_viewers, 60);

    // Getting current online user_ids
    foreach ($new_viewers as $new_viewer => $new_time) {
      $user_ids[] = $new_viewer;
    }

    // Getting user details using user id
    $get_users_by_ids = $ci->user_model->get_users_by_ids($user_ids);
    return $get_users_by_ids['result'];
  }

  // Return a null array if something wrong
  return NULL;
}

/**
 * Add toast notification
 * 
 */
function add_toast_notificaion($user_id = 0, $notify_text = NULL, $post_id = NULL) {

  $ci = & get_instance();

  if (empty($user_id)) {
    if (isset($ci->current_user['user_id'])) {
      $user_id = $ci->current_user['user_id'];
    } elseif (isset($ci->mobile_current_user['user_id'])) {
      $user_id = $ci->mobile_current_user['user_id'];
    }
  }

  if (!empty($user_id) && is_numeric($user_id) && !empty($notify_text)) {

    $new_notifications = array();

    // Getting currently existing notificaionst
    $user_notifications = $ci->cache->get('user_notify_' . $user_id);

    if (!empty($user_notifications) && is_array($user_notifications)) {
      foreach ($user_notifications as $notifications) {
        if (!empty($notifications)) {
          $new_notifications[] = $notifications;
        }
      }
    }

    $new_notifications[] = array('date' => date("Y-m-d H:i:s"), 'text' => (string) $notify_text, 'post_id' => (string) $post_id, 'toast' => 0, 'read' => 0);

    // Saving new data to cache variable // 9 hrs => 32400, 1 week => 604800
    return $ci->cache->save('user_notify_' . $user_id, $new_notifications, 604800);
  }

  return FALSE;
}

function get_mentioned_users($string = NULL) {
  $ci = & get_instance();
  $usernames = array();
  preg_match_all('/@([A-Za-z0-9_.]{1,15})/', $string, $usernames);
  if (!empty($usernames[1]) && is_array($usernames[1])) {
    $users = $ci->user_model->get_users_by_usernames($usernames[1]);
    return $users['result'];
  }
  return array();
}

function array_update($array, $key, $value) {
  $narray = array();
  if (is_array($array)) {
    foreach ($array as $akey) {
      $akey[$key] = $value;
      $narray[] = $akey;
    }
  }
  return $narray;
}

function make_post_id($type = NULL, $type_id = NULL) {
  $type_key = NULL;
  $like_arr = array('tweet', 'reply', 'event', 'album', 'photo', 'video', 'poll', 'comment', 'wall_post');
  if (in_array($type, $like_arr) && is_numeric($type_id)) {
    switch ($type) {
      case 'tweet':
        $type_key = 'T';
        break;
      case 'reply':
        $type_key = 'R';
        break;
      case 'event':
        $type_key = 'E';
        break;
      case 'album':
        $type_key = 'A';
        break;
      case 'poll':
        $type_key = 'P';
        break;
      case 'comment':
        $type_key = 'C';
        break;
      case 'photo':
        $type_key = 'PO';
        break;
      case 'video':
        $type_key = 'VO';
        break;
      case 'wall_post':
        $type_key = 'W';
        break;
    }
    return $type_key . $type_id;
  }
  return NULL;
}

function get_album_photos($album_id = 0, $limit = null) {
  $ci = & get_instance();
  $get_photos = $ci->timeline_model->get_album_photos($album_id, $limit);
  $result = array();
  $result['photos'] = $get_photos['result'];
  $result['count'] = $get_photos['count'];
  $result['total'] = $ci->db->where('photo_album_id', $album_id)->count_all_results('albums_photos');
  return $result;
}

function get_poll_options($poll_id = 0) {
  $ci = & get_instance();
  $get_options = $ci->timeline_model->get_poll_options($poll_id);
  $result = array();
  $result['options'] = $get_options['result'];
  $result['votes'] = $ci->db->where('poll_reply_poll_id', $poll_id)->count_all_results('polls_reply');
  return $result;
}

?>